package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.qingcheng.pojo.goods.Category;
import com.qingcheng.pojo.goods.Sku;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.goods.CategoryService;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.PreferentialService;
import com.qingcheng.utils.CacheKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * Created by yuanxin
 * Date:2019/7/16
 * Time:10:37
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Map<String, Object>> findCartList(String username) {
        System.out.println("从Redis中提取购物车" + username);
        List<Map<String, Object>> cartList = (List<Map<String, Object>>) redisTemplate.boundHashOps(CacheKey.CART_LIST).get(username);
        if (cartList == null) {
            cartList = new ArrayList<>();
        }
        return cartList;
    }

    @Reference
    private CategoryService categoryService;
    @Reference
    private SkuService skuService;

    @Override
    public void addItem(String username, String skuId, Integer num) {
        //实现思路：遍历购物车，如果购物车中存在该商品则累加数量，如果不存在则添加购物车项
        //获取购物车
//        CopyOnWriteArrayList<Map<String, Object>> cartList = (CopyOnWriteArrayList<Map<String, Object>>) findCartList(username);
        List<Map<String, Object>> cartList1 = findCartList(username);
        Object[] objects = cartList1.toArray();
        CopyOnWriteArrayList<Map<String, Object>> cartList = new CopyOnWriteArrayList(objects);
        //是否在购物车中存在
        boolean flag = false;
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");
            if (skuId.equals(orderItem.getSkuId())) {//购物车存在该商品
                if (orderItem.getNum() <= 0) {//如果数量小于等于0
                    cartList.remove(map);//购物车项删除-------有可能引发并发修改异常,建议使用CopyOnWriteArrayList
                    flag = true;
                    break;
                }
                //单个商品重量
                Integer weight = orderItem.getWeight() / orderItem.getNum();
                orderItem.setNum(orderItem.getNum() + num);//数量累加
                orderItem.setMoney(orderItem.getNum() * orderItem.getPrice());//金额计算


                if (orderItem.getNum() <= 0) {
                    cartList.remove(map);
                }
                flag = true;
                break;
            }
        }
        if (flag == false) {
            Sku sku = skuService.findById(skuId);
            if (sku == null) {
                throw new RuntimeException("商品不存在");
            }
            if (!"1".equals(sku.getStatus())) {
                throw new RuntimeException("商品状态不合法");
            }
            if (num <= 0) {//数量不能为0或负数
                throw new RuntimeException("商品数量不合法");
            }
            OrderItem orderItem = new OrderItem();

            orderItem.setSkuId(skuId);
            orderItem.setSpuId(sku.getSpuId());
            orderItem.setNum(num);
            orderItem.setImage(sku.getImage());
            orderItem.setPrice(sku.getPrice());
            orderItem.setName(sku.getName());
            orderItem.setMoney(orderItem.getPrice() * num);//金额计算
            if (sku.getWeight() == null) {
                sku.setWeight(0);
            }
            orderItem.setWeight(sku.getWeight() * num);//重量计算

            orderItem.setCategoryId3(sku.getCategoryId());
            Category category3 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGROY).get(sku.getCategoryId());
            if (category3 == null) {
                category3 = categoryService.findById(sku.getCategoryId());//根据3级分类Id查找3级分类
                redisTemplate.boundHashOps(CacheKey.CATEGROY).put(sku.getCategoryId(), category3);
            }
            orderItem.setCategoryId2(category3.getParentId());//根据3级分类拿到2级分类ID

            Category category2 = (Category) redisTemplate.boundHashOps(CacheKey.CATEGROY).get(category3.getParentId());
            if (category2 == null) {
                category2 = categoryService.findById(category3.getParentId());//根据2级分类Id查找2级分类
                redisTemplate.boundHashOps(CacheKey.CATEGROY).put(category3.getParentId(), category2);
            }
            orderItem.setCategoryId1(category2.getParentId());//根据2级分类拿到1级分类ID

            Map<String, Object> map = new HashMap<>();
            map.put("item", orderItem);
            map.put("checked", true);

            cartList.add(map);
        }
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username, cartList);
    }

    @Override
    public boolean updateChecked(String username, String skuId, boolean checked) {
        //获取购物车
        List<Map<String, Object>> cartList = findCartList(username);
        boolean isOk = false;
        for (Map<String, Object> map : cartList) {
            OrderItem orderItem = (OrderItem) map.get("item");
            if (skuId.equals(orderItem.getSkuId())) {
                map.put("checked", checked);
                isOk = true;//执行成功
                //存入缓存
                redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username, cartList);
                break;
            }
        }
        return isOk;
    }

    @Override
    public void deleteCheckedCart(String username) {
        //获取未选中的购物车
        List<Map<String, Object>> cartList = findCartList(username).stream()
                .filter(cart -> (boolean) cart.get("checked") == false)
                .collect(Collectors.toList());
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username, cartList);
    }

    @Autowired
    private PreferentialService preferentialService;

    @Override
    public Map<Integer, Object> preferential(String username) {
        //获取选中的购物车 List<OrderItem>   list<Map>(item,checked)
        List<OrderItem> orderItemList = findCartList(username).stream()
                .filter(cart -> (boolean) cart.get("checked"))
                .map(cart -> (OrderItem) cart.get("item"))
                .collect(Collectors.toList());

        //按分类聚合统计每个分类的金额
        Map<Integer, IntSummaryStatistics> cartMap = orderItemList.stream()
                .collect(Collectors.groupingBy(OrderItem::getCategoryId3, Collectors.summarizingInt(OrderItem::getMoney)));

        //循环结果,统计每个分类的优惠金额,并累加
        Map<Integer, Object> preMoneyMap = new HashMap<>();
        for (Integer categoryId : cartMap.keySet()) {
            //获取品类的消费金额
            int money = (int) cartMap.get(categoryId).getSum();
            //获取品类的优惠金额
            int preMoney = preferentialService.findPreMoneyByCategoryId(categoryId, money);
            preMoneyMap.put(categoryId,preMoney);
            System.out.println("分类: " + categoryId + "消费金额: " + money + "优惠金额: " + preMoney);
        }
        return preMoneyMap;
    }

    @Override
    public List<Map<String, Object>> findNewOrderItemList(String username) {
        List<Map<String, Object>> cartList = findCartList(username);
        for (Map<String, Object> cart : cartList) {
            OrderItem orderItem = (OrderItem) cart.get("item");
            Sku sku = skuService.findById(orderItem.getSkuId());
            orderItem.setPrice(sku.getPrice());//更新价格
            orderItem.setMoney(sku.getPrice()*orderItem.getNum());//更新金额
        }
        redisTemplate.boundHashOps(CacheKey.CART_LIST).put(username,cartList);//放入缓存
        return cartList;
    }
}
